/** 
	# Map js. 
*/

Map = Class.extend({
	
	/**
	 * Check if browser is supported geo location.
	 */
	init: function()	{
		this.map=null;
	    this.geocoder = new google.maps.Geocoder();
	    this.mylat;
	    this.mylng;
	    this.mklat;
	    this.mklng;
	    
	    this.directionsDisplay = new google.maps.DirectionsRenderer();
	    this.directionsService = new google.maps.DirectionsService();
	
		this.browserSupported=false;
		this.info = new google.maps.InfoWindow();
		this.infoBox = null;
		this.marker =  new google.maps.Marker();
		this.markersArray = [];
		this.markersArrayPlace = [];
		this.draw_circle = null;
		Map.sys="BROWSER";
	},
	
	
	
	/**
	 * @desc Setting the map
	 */
	setMap: function(div_id, options){
		var myOptions = options || {
			zoom: 14,
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			disableDoubleClickZoom: true
		};
 
		this.map = new google.maps.Map(document.getElementById(div_id), myOptions);
	},
	
	
	/**
	 * @desc Show a position on map.
	 */
	show: function(lat, lng, txt){
		var location = new google.maps.LatLng(lat, lng);
		this.map.setCenter(location);
		this.info.setContent(txt);
		this.info.setPosition(location);
		this.info.open(this.map);
	},
	
	/**
	 * @desc Show a position on map, where arguments is a position Object
	 */
	showLocation: function(position, txt){
		if (!txt){
			txt="Bạn đang ở đây";
		}
		this.show(position.coords.latitude, position.coords.longitude, txt);
	},
	
	/**
	 * @desc Focus a position on map.
	 */
	focus: function(lat, lng){
		var location = new google.maps.LatLng(lat, lng);
		this.map.setCenter(location);
	},
	
	/**
	 * @desc Focus a position on map, where arguments is a position Object
	 */
	focusLocation: function(position){
		this.focus(position.coords.latitude, position.coords.longitude);
	},
	
	/**
	 * @desc Show a marker on map, where arguments is a latlng Object
	 */
	markLatLng: function(location, txt){
		this.marker.setMap(this.map);
	    this.marker.setPosition(location);
	    this.marker.setTitle(txt);
	    this.mklat=location.lat();
	    this.mklng=location.lng();
	},
	
	/**
	 * @desc Show a marker on map, where arguments is a position Object
	 */
	mark: function(lat,lng, txt){
		if (!txt){
			txt="Bạn đang ở đây";
		}
		var latlng = new google.maps.LatLng(lat, lng);
		this.markLatLng(latlng, txt);
	},
	
	/**
	 * @desc Show a marker on map, where arguments is a position Object
	 */
	markLocation: function(position, txt){
		if (!txt){
			txt="Bạn đang ở đây";
		}
		var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
		this.focusLocation(position);
		this.markLatLng(latlng, txt);
	},
	
	/**
	 * @desc add a marker on map with a image
	 */
	
	addMarker: function(lat,lng,img,txt){
		mk =  new google.maps.Marker();
		mk.setMap(this.map);
		var location = new google.maps.LatLng(lat, lng);
		mk.setPosition(location);
		mk.setIcon(img);
		mk.setTitle(txt);
		this.markersArray.push(mk);
	},
	
	deleteAllMarker: function(){
	  if (this.markersArray) {
	    for (i in this.markersArray) {
	    	this.markersArray[i].setMap(null);
	    }
	    this.markersArray.length = 0;
	  }
	},
	
	showUserOnMap: function(userlist){
		var obj = this;
		$.each(userlist,function(index, val){
			if(obj.markersArray.length>0){
				var has = false;
				for (i in obj.markersArray) {
					if(val.lat==obj.markersArray[i].getPosition().lat()&&val.lng==obj.markersArray[i].getPosition().lng()){
						has = true;
					}
			    }
				if(!has){
					if(val.gender==0){
						obj.addMarker(val.lat,val.lng,'static/images/people-female.png');
					}
					else{
						obj.addMarker(val.lat,val.lng,'static/images/people-male.png');
					}
					google.maps.event.addListener(obj.markersArray[obj.markersArray.length-1], 'dblclick', function(){window.location='#page/Profile/id/'+val.id;});
				    var latlng = obj.markersArray[obj.markersArray.length-1].getPosition();
					google.maps.event.addListener(obj.markersArray[obj.markersArray.length-1], 'click', function(){
						if(obj.infoBox != null){
							obj.infoBox.setMap(null);
							obj.infoBox = null;
						}
						var type = 1;
						if(val.gender == 0){
							type=2;
						}
//						txt = '<div class="infobox'+type+'">\
//								<div class="bigbox-top"><img src="static/data/avatar'+val.avatar+'" class="bigbox-img"/><div class="online"></div><div class="bigbox-title">'+val.name+'</div><h5>+<span>'+val.distance+'</span> km</h5></div><div class="bigbox-content"></div></div>';
						var txt = '<a href="#page/Profile/id/'+val.id+'">'+val.name+'</a>';
						obj.infoBox = new InfoBox({type:type,latlng:latlng,map:obj.map,txt:txt});
					});
				}
			}
			else{
				if(val.gender==0){
					obj.addMarker(val.lat,val.lng,'static/images/people-female.png');
				}
				else{
					obj.addMarker(val.lat,val.lng,'static/images/people-male.png');
				}
				google.maps.event.addListener(obj.markersArray[obj.markersArray.length-1], 'dblclick', function(){window.location='#page/Profile/id/'+val.id;});
				var latlng = obj.markersArray[obj.markersArray.length-1].getPosition();
				google.maps.event.addListener(obj.markersArray[obj.markersArray.length-1], 'click', function(){
					if(obj.infoBox != null){
						obj.infoBox.setMap(null);
						obj.infoBox = null;
					}
					var type = 1;
					if(val.gender == 0){
						type=2;
					}
//					txt = '<div class="infobox'+type+'">\
//							<div class="bigbox-top"><img src="static/data/avatar/'+val.avatar+'" class="bigbox-img"/><div class="online"></div><div class="bigbox-title">'+val.name+'</div><h5>+<span>'+val.distance+'</span> km</h5></div><div class="bigbox-content"></div></div>';
					var txt = '<a href="#page/Profile/id/'+val.id+'">'+val.name+'</a>';
					obj.infoBox = new InfoBox({type:type,latlng:latlng,map:obj.map,txt:txt});
				});
			}
		});
		
	},
	
	showFriendOnMap: function(userlist){
		var obj = this;
		$.each(userlist,function(index, val){
			try{
			if(obj.markersArray.length>0){
				var has = false;
				for (i in obj.markersArray) {
					if(val.lat==obj.markersArray[i].getPosition().lat()&&val.lng==obj.markersArray[i].getPosition().lng()){
						has = true;
					}
			    }
				if(!has){
					if(val.gender==0){
						obj.addMarker(val.lat,val.lng,'static/images/friend-female.png');
					}
					else{
						obj.addMarker(val.lat,val.lng,'static/images/friend-male.png');
					}
					google.maps.event.addListener(obj.markersArray[obj.markersArray.length-1], 'dblclick', function(){window.location='#page/Profile/id/'+val.id;});
					var latlng = obj.markersArray[obj.markersArray.length-1].getPosition();
					google.maps.event.addListener(obj.markersArray[obj.markersArray.length-1], 'click', function(){
						if(obj.infoBox != null){
							obj.infoBox.setMap(null);
							obj.infoBox = null;
						}
							var type = 1;
							if(val.gender == 0){
								type=2;
							}
	//						txt = '<div class="infobox'+type+'">\
	//								<div class="bigbox-top"><img src="static/data/avatar/'+val.avatar+'" class="bigbox-img"/><div class="online"></div><div class="bigbox-title">'+val.name+'</div><h5>+<span>'+val.distance+'</span> km</h5></div><div class="bigbox-content"></div></div>';
							var txt = '<a href="#page/Profile/id/'+val.id+'">'+val.name+'</a>';
							obj.infoBox = new InfoBox({type:type,latlng:latlng,map:obj.map,txt:txt});
					});
				}
			}
			else{
				
				if(val.gender==0){
					obj.addMarker(val.lat,val.lng,'static/images/friend-female.png');
				}
				else{
					obj.addMarker(val.lat,val.lng,'static/images/friend-male.png');
				}

				google.maps.event.addListener(obj.markersArray[obj.markersArray.length-1], 'dblclick', function(){window.location='#page/Profile/id/'+val.id;});
				var latlng = obj.markersArray[obj.markersArray.length-1].getPosition();
				var hasInfobox = false;
				google.maps.event.addListener(obj.markersArray[obj.markersArray.length-1], 'click', function(){
					if(obj.infoBox != null){
						obj.infoBox.setMap(null);
						obj.infoBox = null;
					}
						var type = 1;
						if(val.gender == 0){
							type=2;
						}
//						var txt = '<div class="infobox'+type+'">\
//								<div class="bigbox-top"><img src="static/data/avatar/'+val.avatar+'" class="bigbox-img"/><div class="online"></div><div class="bigbox-title">'+val.name+'</div><h5>+<span>'+val.distance+'</span> km</h5></div><div class="bigbox-content"></div></div>';
						var txt = '<a href="#page/Profile/id/'+val.id+'">'+val.name+'</a>';
						obj.infoBox = new InfoBox({type:type,latlng:latlng,map:obj.map,txt:txt});
				});
			}
			}
			catch(err){
				alert(err);
			}
		});
	},
	
	showPlaceOnMap: function(placelist){
		var obj = this;
		$.each(placelist,function(index, val){
			var avatar='default.png';
			if(val.avatar!='') avatar = val.avatar;
			
			if(obj.markersArray.length>0){
				var has = false;
				for (i in obj.markersArray) {
					if(val.lat==obj.markersArray[i].getPosition().lat()&&val.lng==obj.markersArray[i].getPosition().lng()){
						has = true;
					}
			    }
				if(!has){
					obj.addMarker(val.lat,val.lng,'static/images/place-marker.png');
					google.maps.event.addListener(obj.markersArray[obj.markersArray.length-1], 'dblclick', function(){window.location='#page/Place/id/'+val.id;});
					var latlng = obj.markersArray[obj.markersArray.length-1].getPosition();
					google.maps.event.addListener(obj.markersArray[obj.markersArray.length-1], 'click', function(){
						if(obj.infoBox != null){
							obj.infoBox.setMap(null);
							obj.infoBox = null;
						}
//						var txt = '<div class="infobox3>\
//								<div class="smallbox-top">'+val.name+'</div>\
//								+<span>'+val.distance+'</span> km\
//								<div class="smallbox-top">'+val.address+'</div>\
//						</div>'; 
						var txt ='<div><a href="#page/Place/id/'+val.id+'">'+val.name+'</a></div>+<span>'+val.distance+'</span> km';
						obj.infoBox = new InfoBox({type:3,latlng:latlng,map:obj.map,txt:txt});
					});
				}
			}
			else{
				obj.addMarker(val.lat,val.lng,'static/images/place-marker.png');
				google.maps.event.addListener(obj.markersArray[obj.markersArray.length-1], 'dblclick', function(){window.location='#page/Place/id/'+val.id;});
				var latlng = obj.markersArray[obj.markersArray.length-1].getPosition();
				google.maps.event.addListener(obj.markersArray[obj.markersArray.length-1], 'click', function(){
					if(obj.infoBox != null){
						obj.infoBox.setMap(null);
						obj.infoBox = null;
					}
//					var txt = '<div class="infobox3>\
//							<div class="smallbox-top">'+val.name+'</div>\
//							+<span>'+val.distance+'</span> km\
//							<div class="smallbox-top">'+val.address+'</div>\
//					</div>'; 
					var txt ='<a href="#page/Place/id/'+val.id+'">'+val.name+'</a>'+val.distance+' km';
					obj.infoBox = new InfoBox({type:3,latlng:latlng,map:obj.map,txt:txt});
				});
			}
		});
	},
	
	/**
	 * @desc find a address, arguments is the id of input element
	 */
	
	searchAddress: function(address) {
		var obj = this;
		if(address!=''){
		    this.geocoder.geocode( { 'address': address}, function(results, status) {
		      if (status == google.maps.GeocoderStatus.OK) {
		    	  obj.map.setCenter(results[0].geometry.location);
		    	  obj.markLatLng(results[0].geometry.location);
		      } else {
		    	  alert('Không tìm thấy '+address);
		      }
		    });
		}
	},
	
	searchMap: function(input) {
		var address = document.getElementById(input).value;
		if(address!=''){
		    this.geocoder.geocode( { 'address': address}, function(results, status) {
		      if (status == google.maps.GeocoderStatus.OK) {
		    	$('#place-items').html('');
//		    	alert(nearbyplace.typeKey);
		    	this.map.setCenter(results[0].geometry.location);
		    	this.markLatLng(results[0].geometry.location);				
		      } else {
		    	  	alert('Không tìm thấy '+address);
		      }
		    });
		}
	},

	
	/**
	 * @desc Add click event.
	 */
	click: function(fnc){
		 google.maps.event.addListener(this.map, 'click',function(event){
			 fnc(event.latLng);
		 })
	},
	
	/**
	 * @desc Add double click event.
	 */
	dblclick: function(fnc){
		 google.maps.event.addListener(this.map, 'dblclick',function(event){
			 fnc(event.latLng);
		 })
	},
	
	/**
	 * Locate the current user.
	 */
	locate: function(handler){
		if (navigator.geolocation) {
			Map.sys="BROWSER";
			this.userLocationByBrowser(handler);
		}else{
			Map.sys="GOOGLE";
			this.userLocationByGoogle(handler);
		}
	},
	
	/**
	 * Based on Browser.
	 */
	userLocationByBrowser: function(handler){
		var obj = this;
		navigator.geolocation.getCurrentPosition(function(position){
			handler.call(obj, position);
			this.mylat = position.coords.latitude;
			this.mylng = position.coords.longitude;
		}, function(){
			map.notSupported();
		});
	},
	
	
	
	/**
	 * Based on Google.
	 */
	userLocationByGoogle: function(handler){	
		if (google.gears) {
		// Try Google Gears Geolocation
			browserSupportFlag = true;
			var geo = google.gears.factory.create('beta.geolocation');
			geo.getCurrentPosition(function(position) {
				handler(position);
				this.mylat = position.coords.latitude;
				this.mylng = position.coords.longitude;
			}, function(){
				this.notSupported();
			});
		}else{
			this.notSupported();
		}
	},
	
	
	
	/** 
	 * Handling method when geo is not supported.
	 */
	notSupported: function(){
		content.init();
		alert('Không xác định được vị trí');
	},

    /**
     * @desc	Get current latitude and longitude
     * @return	latLngStr
     */
    
    getCurrentLatLng: function(position, div_id){
        $('#'+div_id).val(position.coords.latitude + ", " + position.coords.longitude);
    },

    /**
     * @desc	Reverse Geocoding (Address Lookup)
     * @return	Address return by geocoder (maybe the closest addressable location)
     */
    
    reversePos: function(latLngStr, div_id){
        var pos = latLngStr.split(",", 2);
        var lat = parseFloat(pos[0]);
        var lng = parseFloat(pos[1]);
        
        var latlng = new google.maps.LatLng(lat, lng);
    
        this.geocoder.geocode({'latLng': latlng}, function(results, status){
            if (status == google.maps.GeocoderStatus.OK){
            if (results[0]){
                // temporary alert message for testing
                // we will use div_id to get the data returned
                $('#'+div_id).val(results[0].formatted_address);
            }
            }else{
                alert("Geocoder failed due to: " + status);
            }
        });
    },
    
    /**
     * @desc	Find a path between 2 locations
     */
    
    calcRoute: function(start_id, end_id, mode){
        
        if ((mode != "DRIVING")&&(mode != "WALKING")&&(mode != "BYCLING")){
            mode = "DRIVING";   // as default
        }
        var start = document.getElementById(start_id).value;
        var end = document.getElementById(end_id).value;
        var request = {
            origin:start, 
            destination:end,
            travelMode: google.maps.DirectionsTravelMode[mode]
        };
        
        this.directionsService.route(request, function(response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                // temporary alert message for testing
                /* insert your code here to complete */
                alert("OK");
                
                // this.directionsDisplay.setDirections(response);
            }else{
                alert("Failed");
            }
        });
    },
    
    
    drawCircle: function(center, rad, map){
    	var fill_color="#FF0000";
    	var stroke_color ="#EE0000";
//    	var draw_circle =null;
    	if (map.draw_circle != null) {
          map.draw_circle.setMap(null);
    	}
    	this.draw_circle = new google.maps.Circle({
    		center: center,
    		radius: rad,
    		strokeColor: stroke_color,
    		strokeOpacity: 0.5,
    		strokeWeight: 2,
    		fillColor: fill_color,
    		fillOpacity: 0.02,
    		map: map
       });
      },
    
})